<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <div class="area-header">
        <span class="area-header-title">{{ $t('基金基本信息') }}</span>
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('基金全称')" prop="fundFullName">
            <el-autocomplete
              v-model="form.fundFullName"
              class="inline-input name"
              :fetch-suggestions="fundQuerySearch"
              :placeholder="$t('基金全称')"
              :trigger-on-focus="false"
              :maxlength="100"
              @select="fundHandleSelect"
            >
              <template v-if="enableTyc" slot="append">
                <a @click="fundHandleSelect">{{ $t('查询工商信息') }}</a>
              </template>
            </el-autocomplete>
            <!--            <el-input v-else v-model="form.fundFullName" readonly show-word-limit maxlength="100">
              <template slot="append" @click="fundHandleSelect">
                <a @click="fundHandleSelect">{{ $t('查询工商信息') }}</a>
              </template>
            </el-input>-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金简称')" prop="fundName">
            <el-input v-model="form.fundName" :placeholder="$t('基金简称')" show-word-limit :maxlength="50">
              <template v-if="form.id" slot="append">
                <span @click="chartOpenHandle">{{ $t('查看投资架构图') }}</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="getShowEn" :span="12">
          <el-form-item :label="$t('基金名称En')" prop="fundNameEn">
            <el-input v-model="form.fundNameEn" :placeholder="$t('基金名称En')" show-word-limit maxlength="500" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金状态')" prop="fundBaseFund.fundStatus">
            <dictSelect
              v-model="form.fundBaseFund.fundStatus"
              :clearable="true"
              dictionary="fund_status"
              :disabled="fundStatusModify"
            />
          </el-form-item>
        </el-col>
        <!-- 其他投资基金 -->
        <el-col :span="8">
          <el-form-item :label="$t('基金类型')" prop="fundBaseFund.fundType" class="fund-type-left-select">
            <el-select v-model="form.fundBaseFund.fundType" :clearable="true" :placeholder="$t('基金类型')">
              <el-option
                v-for="dict in fundTypeOption"
                :key="dict.id"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item prop="fundBaseFund.fundTypeSub" class="fund-type-left-right">
            <el-select v-model="form.fundBaseFund.fundTypeSub" :clearable="true" style="margin-top: 36px !important;">
              <el-option
                v-for="dict in fundTypeSubOption"
                :key="dict.id"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金目标募集规模') + $t('金额单位')" prop="fundBaseFund.targetAmount">
            <Money v-model="form.fundBaseFund.targetAmount" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金负责人')" prop="personCharge">
            <user-select v-model="form.personCharge" :placeholder="$t('基金负责人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('币种')" prop="currency">
            <dictSelect
              v-model="form.currency"
              :clearable="true"
              dictionary="currency"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金成立日')" prop="foundationDate">
            <DatePicker
              v-model="form.foundationDate"
              :placeholder="$t('基金成立日')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('企业统一社会信用代码')" prop="creditCode">
            <el-input v-model="form.creditCode" :placeholder="$t('企业统一社会信用代码')" show-word-limit maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金编码')" prop="fundBaseFund.sCode">
            <el-input v-model="form.fundBaseFund.sCode" :placeholder="$t('S码')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <areaCascader ref="areaCascader" :bus-data="form" :field="{ province: 'provinceRegistered',city: 'cityRegistered',area: 'districtRegistered' }" />
        <el-col :span="12">
          <el-form-item :label="$t('基金投资方式')" prop="fundBaseFund.investmentMode">
            <el-select v-model="form.fundBaseFund.investmentMode" :placeholder="$t('基金投资方式')">
              <el-option
                v-for="(dict, index) in investmentWayOption"
                :key="index"
                :value="dict.dictValue"
                :label="$t(dict.dictLabel)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.fundBaseFund.investmentMode === 'QT'" :span="12">
          <el-form-item :label="$t('其它类型')" prop="fundBaseFund.otherMode">
            <el-input v-model="form.fundBaseFund.otherMode" :placeholder="$t('其它类型')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金管理人')" prop="fundBaseFund.managerId">
            <MainBodySelect
              v-model="form.fundBaseFund.managerId"
              :parameters="!managerOpen ? 'manager' : ''"
              style="float: left; width: 100%;z-index: 1000 !important;"
            />
            <div class="addGLR" @click="addManager">
              <span class="addGLRText">{{ $t('添加管理人') }}</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('GP')" prop="gpIds">
            <el-select v-model="form.gpIds" multiple :placeholder="$t('请选择')" filterable>
              <el-option
                v-for="item in gpBaseOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <div class="addGLR" style="top: 0;" @click="addGp">
              <span class="addGLRText">{{ $t('添加GP') }}</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('管理类型')" prop="managementType">
            <el-select v-model="form.managementType" :placeholder="$t('管理类型')">
              <el-option
                v-for="(dict, index) in managementOption"
                :key="index"
                :value="dict.dictValue"
                :label="$t(dict.dictLabel)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('投委会成员')" prop="committeePeople">
            <el-input v-model="form.fundBaseFund.committeePeople" :placeholder="$t('投委会成员')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金运作方式')" prop="operationMode">
            <el-input v-model="form.fundBaseFund.operationMode" :placeholder="$t('基金运作方式')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金托管人')" prop="custodian">
            <el-input v-model="form.fundBaseFund.custodian" :placeholder="$t('基金托管人')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="getShowEn" :span="12">
          <el-form-item :label="$t('基金托管人En')" prop="custodianEn">
            <el-input v-model="form.fundBaseFund.custodianEn" :placeholder="$t('基金托管人En')" show-word-limit maxlength="500" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金份额总额')" prop="fundTotalShare">
            <el-input v-model="form.fundBaseFund.fundTotalShare" :placeholder="$t('基金份额总额')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金合同存续期')" prop="durationContract">
            <el-input v-model="form.fundBaseFund.durationContract" :placeholder="$t('基金合同存续期')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="getShowEn" :span="12">
          <el-form-item :label="$t('基金合同存续期En')" prop="durationContractEn">
            <el-input v-model="form.fundBaseFund.durationContractEn" :placeholder="$t('基金合同存续期En')" show-word-limit maxlength="500" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('组织形式')" prop="organizationalForm">
            <el-select v-model="form.fundBaseFund.organizationalForm" :placeholder="$t('组织形式')" clearable>
              <el-option
                v-for="item in organizationalFormOption"
                :key="item.id"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合作律师事务所')" prop="cooperativeLawFirm">
            <el-input v-model="form.cooperativeLawFirm" :placeholder="$t('合作律师事务所')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金关账日')" prop="fundClosingDate">
            <DatePicker
              v-model="form.fundClosingDate"
              :placeholder="$t('基金关账日')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('审计师')" prop="auditor">
            <el-input v-model="form.auditor" :placeholder="$t('审计师')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="getShowEn" :span="12">
          <el-form-item :label="$t('审计师En')" prop="auditorEn">
            <el-input v-model="form.auditorEn" :placeholder="$t('审计师En')" show-word-limit maxlength="500" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('投资目标')" prop="investmentObjective">
            <el-input v-model="form.investmentObjective" type="textarea" :placeholder="$t('投资目标')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="area-header">
        <span class="area-header-title">{{ $t('基金期限') }}</span>
      </div>
      <el-table
        :data="form.fundPhaseList"
        border
        class="nowrapTable formTable"
      >
        <el-table-column prop="phase" :label="$t('阶段')">
          <template slot-scope="scope">
            <el-form-item :prop="'fundPhaseList.' + scope.$index + '.phase'">
              <dictSelect
                v-model="scope.row.phase"
                :clearable="true"
                dictionary="fund_phase"
                @change="phaseChange($event, scope.$index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="year" :label="$t('期限(年)')">
          <template slot-scope="scope">
            <el-form-item prop="year">
              <el-input-number v-model="scope.row.year" :precision="1" :min="0" :max="1000" :placeholder="$t('期限(年)')" @change="yearChange(scope.row, scope.$index)" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" :label="$t('起始日期')">
          <template slot-scope="scope">
            <el-form-item prop="startDate">
              <DatePicker
                v-model="scope.row.startDate"
                type="date"
                :placeholder="$t('起始日期')"
                @change="startDateChange(scope.row, scope.$index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="endDate" :label="$t('结束日期')">
          <template slot-scope="scope">
            <el-form-item prop="endDate">
              <DatePicker
                v-model="scope.row.endDate"
                :placeholder="$t('结束日期')"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('计提基数')" prop="accrualBase">
          <template slot-scope="scope">
            <el-form-item prop="accrualBase">
              <dict-select
                v-model="scope.row.accrualBase"
                dictionary="accrual_base"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!--<el-table-column :label="$t('管理费比例(%)')" prop="managementFeeRatio">
          <template slot-scope="scope">
            <el-form-item prop="managementFeeRatio">
              <Ratio v-model="scope.row.managementFeeRatio" :controls="false" :min="0" :max="100" :precision="2" />
            </el-form-item>
          </template>
        </el-table-column>-->
        <el-table-column :label="$t('操作')" align="center" width="80">
          <template slot-scope="scope">
            <el-button v-hasPermi="['fund:fundbase:remove']" size="mini" type="text" icon="el-icon-delete" @click="delFundPhase(scope.$index)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button v-hasPermi="['fund:fundbase:edit']" type="primary" icon="el-icon-plus" size="mini" @click="addFundPhase">{{ $t("添加") }}</el-button>
      </div>
      <FileTable :list.sync="form.fileList" has-permi="fund:fundbase" data-type="fund_base" :business-type="'fund'" :file-config-type="'fund_base_' + form.fundBaseFund.fundStatus" select-business-data="false" :btn-show="!otherBtnHide" />
    </el-form>
    <div v-show="!btnHide" slot="footer" class="dialog-footer" style="text-align: center; margin-top: 10px;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn v-if="btnShow" has-permi="fund:fundbase" :cancel-show="openLocation === undefined" />
    </div>
    <el-dialog :title="$t('投资架构图')" :visible.sync="chartOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <invest-structure-chart :chart-data="chartData" />
    </el-dialog>
    <!-- 快速添加管理人 -->
    <el-dialog :title="$t('基金管理人')" :visible.sync="managerOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <gpBaseForm ref="gpBaseForm" @successSaveManager="successSaveManager" />
    </el-dialog>
  </div>
</template>
<script>
import {
  saveFundBase,
  getFundBase,
  fundInfoByFundName,
  fundInfoByFundFullName,
  fundDetailsByName,
  fundListByName,
  fundInvestChartData
} from '@/api/fund/fundBase'
    import MainBodySelect from '@/components/MainBodySelect'
    import investStructureChart from '@/views/deal/base/investStructureChart'
    import gpBaseForm from '@/views/fund/gpBase/gpBaseForm.vue'
    // 省市组件
    import areaCascader from '@/components/Area/cascader.vue'
    import { findTrueGp } from '@/api/fund/gp/gpBase'
    export default {
      components: {
        MainBodySelect,
        areaCascader,
        investStructureChart,
        gpBaseForm
      },
      props: {
          fundBaseData: {
            type: Array,
            default: () => []
          },
          btnShow: {
            type: Boolean,
            default: true,
            desc: '是否展示按钮'
          },
          // 基金类型 fund, fof
          fundDataType: {
            type: String,
            default: 'fund'
          }
        },
      data() {
          return {
              otherBtnHide: false,
              // 是否隐藏保存等按钮
              btnHide: false,
              // 表单参数
              form: {
                fundBaseFund: {
                  fundStatus: ''
                },
                fileList: []
              },
              // 基金状态是否可以修改
              fundStatusModify: false,
              // 遮罩层
              loading: false,
              // 基金投资方式字典
              investmentWayOption: [],
              // GP管理人
              gpBaseOptions: [],
              // 基金管理类型字典
              managementOption: [],
              // 天眼查查询条件
              tycParam: {
                id: '',
                fundFullName: '',
                tycId: ''
              },
              // 表单校验
              rules: {
                fundName: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' },
                  { validator: this.checkFundName, trigger: 'blur' }
                ],
                fundFullName: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' },
                  { validator: this.checkFundFullName, trigger: 'blur' }
                ],
                'fundBaseFund.fundStatus': [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                'fundBaseFund.fundType': [
                  { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                ],
                'fundBaseFund.fundTypeSub': [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
                'fundBaseFund.organizationalForm': [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
                'fundBaseFund.targetAmount': [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ],
                currency: [
                  { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                ],
                personCharge: [
                  { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                ],
                'fundBaseFund.managerId': [
                  { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                ],
                foundationDate: [
                  { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                ]
              },
              managerOpen: false,
              openLocation: undefined,
              chartOpen: false,
              chartData: [],
              fundTypeOption: [],
              fundTypeSubOption: [],
              organizationalFormOption: [],
              enableTyc: undefined
          }
      },
      computed: {
        getShowEn() {
          if (this.$store.state.app.showEn === 'true') {
            return true
          } else {
            return false
          }
        }
      },
      watch: {
        fundBaseData: function() {
          this.form = this.fundBaseData
        }
      },
      mounted() {
          this.$bus.$emit('async_done')
          this.enableTyc = (window.localStorage.getItem('enableTyc') === 'true')
      },
      created() {
        this.getDicts('fund_nvestment_way').then(response => {
          this.investmentWayOption = response.data
        })
        this.getDicts('fund_management_type').then(response => {
          this.managementOption = response.data
        })
        this.getDicts('fund_type').then(response => {
          this.fundTypeOption = response.data
        })
        this.getDicts('fund_type_sub').then(response => {
          this.fundTypeSubOption = response.data
        })
        this.getDicts('fund_organizational_form').then(response => {
          this.organizationalFormOption = response.data
        })
        // 查询GP管理人类型为GP
        this.findGpOption()
      },
      methods: {
        // 初始化数据
        async init(data) {
          this.loading = true
          if (data !== undefined && data.id !== null && data.id !== undefined) {
            getFundBase(data.id).then(response => {
                this.form = response.data
                this.loading = false
            })
          } else {
            this.reset(data)
            // 初始化阶段数据
            this.initPhaseData()
          }
        },
        findGpOption() {
          findTrueGp().then(response => {
            this.gpBaseOptions = response.data
            console.log(this.gpBaseOptions)
          })
        },
        // 表单重置
        reset(data) {
          if (data !== undefined && data.fundStatus !== undefined) {
            this.fundStatusModify = true
          } else {
            data = { fundStatus: 'CB' }
          }
          this.form = {
            id: undefined,
            fundName: undefined,
            fundNameEn: undefined,
            fundNamePinyin: undefined,
            dataType: this.fundDataType,
            gpIds: [],
            creditCode: undefined,
            provinceRegistered: undefined,
            cityRegistered: undefined,
            districtRegistered: undefined,
            registeredAddress: undefined,
            foundationDate: new Date(),
            duration: undefined,
            investmentPeriod: undefined,
            dueDate: undefined,
            settlingDate: undefined,
            investOriginDate: undefined,
            investDueDate: undefined,
            extensionPeriod: undefined,
            extensionOriginDate: undefined,
            extensionDueDate: undefined,
            currency: 'CNY',
            investmentObjective: undefined,
            cooperativeLawFirm: undefined,
            fileList: [],
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            fundClosingDate: undefined,
            auditor: undefined,
            auditorEn: undefined,
            remark: undefined,
            delFlag: undefined,
            fundPhaseList: [],
            fundBaseFund: {
              fundStatus: data.fundStatus,
              fundType: undefined,
              sCode: undefined,
              investmentMode: undefined,
              otherMode: undefined,
              targetAmount: 0,
              managerId: undefined,
              durationContract: undefined,
              durationContractEn: undefined,
              fundTotalShare: undefined,
              custodian: undefined,
              custodianEn: undefined,
              operationMode: undefined,
              committeePeople: undefined,
              fundTypeSub: 'investment'
            },
            personCharge: this.$store.state.user.userId
          }
            this.resetForm('form')
        },
        // 取消按钮
        cancel() {
            this.$parent.$parent.formOpen = false
            this.$parent.$parent.reset()
        },
        // 关闭form页面
        closeForm() {
            // 关闭form页面遮罩层
            this.loading = false
            // 关闭form页面
            this.$parent.$parent.formOpen = false
            // 刷新list页面
            this.$parent.$parent.getList()
            if (this.$parent.$parent.getViewList !== undefined) {
              this.$parent.$parent.getViewList()
            }
        },
        // 初始化阶段数据
        initPhaseData() {
          this.getDicts('fund_phase').then(response => {
            for (var i = 0; i < response.data.length; i++) {
              var phaseData = {
                phase: response.data[i].dictValue,
                year: undefined,
                startDate: undefined,
                endDate: undefined
              }
              this.form.fundPhaseList.push(phaseData)
            }
            this.loading = false
          })
        },
        /** 提交按钮 */
        submitForm: function() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                  for (let i = 1; (i < this.form.fundPhaseList.length && this.form.fundPhaseList.length > 1); i++) {
                    // 起始时间和结束时间是否都有值
                    var timeNotEmpty = this.form.fundPhaseList[i].startDate && this.form.fundPhaseList[i - 1].endDate

                    // 下一阶段的起始日期是否小于上一阶段的结束日期
                    var timeCompare = new Date(this.form.fundPhaseList[i].startDate) < this.form.fundPhaseList[i - 1].endDate

                    if (timeNotEmpty && timeCompare) {
                      this.$message({
                        message: this.$t('基金期限下一阶段的起始日期不能小于上一阶段的结束日期'),
                        type: 'warning'
                      })
                      return
                    }
                  }
                    this.loading = true
                    saveFundBase(this.form).then(response => {
                        if (response.code === 200) {
                            this.msgSuccess(this.$t('保存成功'))
                            // 如果是通过基金home页面的路由打开，保存时不调用刷新list页面的方法
                            if (this.$parent.$parent.homeOpen) {
                              this.$parent.$parent.homeOpen = false
                            } else if (this.openLocation === 'Home') {
                              // 基金里边保存
                              this.loading = false
                            } else {
                              this.closeForm()
                              this.reset()
                            }
                        } else {
                            this.msgError(response.msg)
                        }
                        this.loading = false
                    })
                } else {
                  this.locationError(document)
                }
            })
        },
        // 校验基金简称是否存在重复
        async checkFundName(rule, value, callback) {
          if (this.form.fundName.trim() === '') {
            callback(new Error(this.$t('请输入基金简称')))
          }
          var fundList = await fundInfoByFundName(this.form.fundName)
          if ((fundList.data.length > 0 && this.form.id === undefined) || (fundList.data.length > 1 && this.form.id !== undefined)) {
            callback(new Error(this.$t('基金简称不能重复')))
          } else {
            callback()
          }
        },
        // 校验基金全称是否存在重复
        async checkFundFullName(rule, value, callback) {
          if (this.form.fundFullName.trim() === '') {
            callback(new Error(this.$t('请输入基金全称')))
          }
          var fundList = await fundInfoByFundFullName(this.form.fundFullName)
          if ((fundList.data.length > 0 && this.form.id === undefined) || (fundList.data.length > 1 && this.form.id !== undefined)) {
            callback(new Error(this.$t('基金全称不能重复')))
          } else {
            callback()
          }
        },
        // 根据期限(年)和起始日期计算结束日期
        yearChange(row, index) {
          // 是否为1开头的正整数
          var reg = /^[1-9]+$/
          // 如果年份是正整数 并且起始日期不为空 就根据起始日期和年份计算结束日期
          if (reg.test(row.year)) {
            if (this.endDateChange(row, index) && row.startDate) {
              const current = Object.assign({}, row)
              var date = new Date(current.startDate)
              date.setFullYear(date.getFullYear() + Number(row.year))
              date.setDate(date.getDate() - 1)
              current.endDate = date
              this.$set(this.form.fundPhaseList, index, current)
            }
          }
        },
        startDateChange(row, index) {
          this.yearChange(row, index)
          this.checkDate(row, index)
        },
        endDateChange(row, index) {
          if (this.checkDate(row, index)) {
            if (index !== 0) {
              const prev = Object.assign({}, this.form.fundPhaseList[index - 1])
              if (prev.endDate) {
                const current = Object.assign({}, this.form.fundPhaseList[index])
                prev.endDate = new Date(prev.endDate)
                prev.endDate.setDate(prev.endDate.getDate() + 1)
                current.startDate = prev.endDate
                // 设置当前行的结束日期
                const date = new Date(current.startDate)
                date.setFullYear(date.getFullYear() + Number(row.year))
                date.setDate(date.getDate() - 1)
                current.endDate = date
                this.$set(this.form.fundPhaseList, index, current)
              }
            }
            return true
          }
          return false
        },
        // 检查日期是否合格
        checkDate(row, index) {
          const current = Object.assign({}, this.form.fundPhaseList[index])
          if (index !== 0) {
            // const prev = Object.assign({}, this.form.fundPhaseList[index - 1])
            // let flag = true
            if (current.startDate && current.endDate && this.compareDate(current.startDate, current.endDate)) {
              this.$message({
                message: this.$t('起始日期不能大于结束日期'),
                type: 'warning'
              })
              current.endDate = undefined
              this.$set(this.form.fundPhaseList, index, current)
              return false
            }
          } else {
            if (current.startDate && current.endDate && this.compareDate(current.startDate, current.endDate)) {
              this.$message({
                message: this.$t('起始日期不能大于结束日期'),
                type: 'warning'
              })
              current.endDate = undefined
              this.$set(this.form.fundPhaseList, index, current)
              return false
            }
          }
          return true
        },
        // 比较日期大小
        compareDate(date1, date2) {
          const formatDate1 = new Date(date1)
          const formatDate2 = new Date(date2)
          return formatDate1 > formatDate2
        },
        // 天眼查查询
        fundQuerySearch(queryString, cb) {
          fundListByName(queryString).then(res => {
            if (res.code === 200) {
              cb(res.data)
            }
          })
        },
        formCleaing() {
          this.form.fundName = ''
          this.form.creditCode = ''
          this.form.foundationDate = ''
          this.form.provinceRegistered = ''
          this.form.cityRegistered = ''
          this.form.tycId = ''
          this.form.logoInfo = ''
        },
        // 基金选择后事件
        fundHandleSelect(item) {
          var fundFullName = this.form.fundFullName
          if (fundFullName === '' || fundFullName === undefined) {
            this.msgError(this.$t('请先输入基金全称!'))
            return
          }
          this.formCleaing()
          this.tycParam.id = this.form.id
          this.tycParam.tycId = item.id
          this.tycParam.fundFullName = fundFullName
           this.tycParam.orgType = item.type
          fundDetailsByName(this.tycParam).then(res => {
            if (res.msg === 'nofind') {
              this.form.fundFullName = ''
              this.msgError(this.$t('天眼查没有获取到该基金信息!'))
            } else {
              // 基金简称
              this.form.fundName = fundFullName
              // 企业统一社会信用代码
              this.form.creditCode = res.data.creditCode
              // 成立时间
              this.form.foundationDate = res.data.setDate
              // 注册地-省
              this.form.provinceRegistered = res.data.provinceRegistered
              this.form.cityRegistered = res.data.cityRegistered
              // 注册区
              this.form.districtRegistered = res.data.registerDistrict
              // 天眼查ID
              this.form.tycId = res.data.tycId
              // 基金logo
              this.form.logoInfo = res.data.logo
              this.msgSuccess(this.$t('已获取工商信息!'))
            }
          })
        },
        delFundPhase(index) {
          this.form.fundPhaseList.splice(index, 1)
        },
        addFundPhase() {
          const row = {
            id: undefined,
            phase: undefined,
            year: undefined,
            startDate: undefined,
            endDate: undefined,
            accrualBase: undefined,
            managementFeeRatio: undefined
          }
          if (!(this.form.fundPhaseList instanceof Array)) {
            this.$set(this.form, 'fundPhaseList', [])
          }
          this.$nextTick(() => {
            this.form.fundPhaseList.push(row)
          })
        },
        phaseChange(val, index) {
          this.$nextTick(() => {
            this.form.fundPhaseList.forEach((item, i) => {
              if (i !== index && val === item.phase) {
                this.$set(this.form.fundPhaseList[index], 'phase', undefined)
                this.$message({
                  type: 'warning',
                  message: this.$t('阶段不能重复')
                })
              }
            })
          })
        },
        chartOpenHandle() {
          this.chartOpen = true
          fundInvestChartData(this.form.id).then(res => {
            this.chartData = res.data
          })
        },
        addManager() {
          console.log('添加管理人')
          this.managerOpen = true
          this.$nextTick(() => {
            this.$refs.gpBaseForm.init(null)
            this.$refs.gpBaseForm.form.type = 'NB'
            this.$refs.gpBaseForm.form.busType = 'MANAGER'
          })
        },
        addGp() {
          console.log('添加GP')
          this.managerOpen = true
          this.$nextTick(() => {
            this.$refs.gpBaseForm.init(null)
            this.$refs.gpBaseForm.form.type = 'NB'
            this.$refs.gpBaseForm.form.busType = 'GP'
          })
        },
        successSaveManager(data) {
          console.log(data, '管理人已成功添加')
          if (this.$refs.gpBaseForm.form.busType === 'GP') {
            this.findGpOption()
            this.form.gpIds = [data.id]
          } else {
            this.form.fundBaseFund.managerId = data.id
          }
        }
      }
    }
</script>
<style type="text/scss" lang="scss" scoped>
.addGLR {
  height: 36px;
  position: absolute;
  right: 30px;
  z-index: 1 !important;
  border: 1px solid #dcdfe6;
  border-top-right-radius: 3px;
  border-bottom-right-radius: 3px;
  background-color: #f5f7fa;
  color: #9e9898;
}
.addGLRText {
  padding: 0 10px;
  cursor: pointer;
  color: inherit;
  text-decoration: none;
  font-size: 14px;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, SimSun, sans-serif;
}
.fund-type-left-select {
  ::v-deep .el-form-item__content {
    padding-right: 0 !important;
  }
  ::v-deep input {
    border-right: 0.1px solid #dcdfe6;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }
}
.fund-type-left-right {
  ::v-deep input {
    border-left: 0.1px solid #dcdfe6;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
  label {
    display: none;
  }
}
</style>
